<template>
  <div class="app-container activity-page">
    <!-- 顶部标题和搜索栏 -->
    <div class="header-section">
      <div class="title-container">
        <h1 class="page-title">乡村活动推荐</h1>
        <p class="page-subtitle">体验乡村文化，参与特色活动</p>
      </div>
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索活动名称或类型..."
          class="search-input"
          clearable
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchActivity">搜索</el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-tags">
        <el-tag
          v-for="tag in tags"
          :key="tag"
          :type="activeTag === tag ? 'primary' : ''"
          @click="filterByTag(tag)"
        >
          {{ tag }}
        </el-tag>
      </div>
      <div class="view-toggle">
        <el-radio-group v-model="viewMode" size="medium">
          <el-radio-button label="list">
            <i class="el-icon-menu"></i> 列表视图
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 活动列表区域 -->
    <div class="activity-list" v-if="viewMode === 'list'">
      <div class="activity-cards">
        <el-card
          v-for="activity in filteredActivities"
          :key="activity.id"
          class="activity-card"
          shadow="hover"
        >
          <div class="card-content">
            <div class="activity-image">
              <!-- 使用image-preview组件展示图片 -->
              <image-preview
                :src="getMainImage(activity.imageUrls)"
                :width="300"
                :height="200"
                @click="viewImageDetail(activity.imageUrls)"
              />
              <div class="activity-badge" :class="activity.type === '文化活动' ? 'culture-badge' : 'life-badge'">
                {{ activity.type }}
              </div>
            </div>
            <div class="activity-info">
              <h3 class="activity-name">{{ activity.title }}</h3>
              <div class="activity-time">
                <i class="el-icon-time"></i>
                <span>{{ formatDate(activity.startTime) }} - {{ formatDate(activity.endTime) }}</span>
              </div>
              <!-- 使用v-html渲染处理后的富文本内容 -->
              <div class="activity-intro" v-html="formatContent(activity.content || '暂无活动详情')"></div>
              <div class="activity-actions">
                <el-button type="primary" size="small" @click="viewDetail(activity.id)">
                  查看详情
                </el-button>
                <el-button type="text" icon="el-icon-share">分享</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>


    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="activities.length"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { listActivity } from "@/api/system/activity";
import imagePreview from "@/components/ImagePreview"; // 引入图片预览组件

export default {
  name: "VillageActivityRecommendation",
  components: {
    imagePreview
  },
  data() {
    return {
      activities: [], // 所有活动数据
      filteredActivities: [], // 过滤后的活动数据
      searchQuery: "",
      activeTag: "全部",
      tags: ["全部", "文化活动", "村民生活", "节庆活动", "体验活动"],
      viewMode: "list", // 视图模式: list
      pageSize: 8,
      currentPage: 1,
      baseUrl: process.env.VUE_APP_IMAGE_SERVER, // 动态获取图片服务器地址
    };
  },
  mounted() {
    this.fetchActivityData();
  },
  methods: {
    // 获取活动数据
    async fetchActivityData() {
      try {
        const response = await listActivity();
        this.activities = response.rows;
        this.filteredActivities = this.activities.slice(0, this.pageSize);
        console.log("过滤后的活动数据为：" + JSON.stringify(this.filteredActivities));
      } catch (error) {
        console.error("获取活动数据失败:", error);
        this.$message.error("获取活动数据失败");
      }
    },

    // 验证日期是否有效
    isValidDate(dateString) {
      const date = new Date(dateString);
      return !isNaN(date.getTime());
    },

    // 搜索活动
    searchActivity() {
      if (!this.searchQuery) {
        this.filteredActivities = this.activities.slice(0, this.pageSize);
        return;
      }

      const query = this.searchQuery.toLowerCase();
      // 搜索时对内容进行反转义后再匹配（避免搜索原始标签）
      this.filteredActivities = this.activities.filter(activity => {
        const content = this.formatContent(activity.content || ''); // 先反转义
        return activity.title.toLowerCase().includes(query) ||
               activity.type.toLowerCase().includes(query) ||
               content.toLowerCase().includes(query);
      }).slice(0, this.pageSize);
    },

    // 按标签筛选
    filterByTag(tag) {
      this.activeTag = tag;
      if (tag === "全部") {
        this.filteredActivities = this.activities.slice(0, this.pageSize);
        return;
      }

      this.filteredActivities = this.activities
        .filter(activity => activity.type === tag)
        .slice(0, this.pageSize);
    },

    // 获取主图
    getMainImage(imageUrls) {
      if (!imageUrls) return null;

      // 处理逗号分隔的多图，取第一张
      const firstUrl = imageUrls
        .split(',')
        .map(url => url.trim())
        .filter(url => url.startsWith('/'))[0]; // 确保以/开头

      return firstUrl ? `${this.baseUrl}${firstUrl}` : null;
    },

    // 查看图片详情
    viewImageDetail(urls) {
      if (urls) {
        // 处理多图情况，转换为数组
        const imageArray = urls
          .split(',')
          .map(url => url.trim())
          .filter(url => url);

        if (imageArray.length > 0) {
          // 传递图片数组和当前查看的索引
          this.$refs.imagePreview.showImages(
            imageArray.map(url => `${this.baseUrl}${url}`),
            0 // 显示第一张图片
          );
        }
      }
    },

    // 格式化富文本内容（核心：HTML反转义）
    formatContent(content) {
      if (!content) return "暂无活动详情";

      // 反转义HTML特殊字符（将 &lt; 转为 <，&gt; 转为 > 等）
      return content
        .replace(/&amp;/g, '&')    // 还原 &
        .replace(/&lt;/g, '<')     // 还原 <
        .replace(/&gt;/g, '>')     // 还原 >
        .replace(/&quot;/g, '"')   // 还原 "
        .replace(/&#039;/g, "'");  // 还原 '
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "未知时间";

      // 尝试多种格式解析
      let date = new Date(dateString);
      if (isNaN(date.getTime())) {
        // 处理带空格的MySQL格式（2025-06-13 12:00:00）
        date = new Date(dateString.replace(' ', 'T'));
      }
      if (isNaN(date.getTime())) {
        // 处理时间戳格式
        date = new Date(Number(dateString));
      }
      if (isNaN(date.getTime())) {
        console.error("无法解析的日期格式:", dateString);
        return "时间格式错误";
      }

      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },

    // 查看详情
    viewDetail(id) {
      this.$router.push({ path: `/activitiesDetail/${id}` });
    },

    // 分页变化
    handlePageChange(page) {
      this.currentPage = page;
      const start = (page - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.filteredActivities = this.activities.slice(start, end);
    }
  }
};
</script>

<style lang="scss" scoped>
// 新增富文本内容样式（确保HTML标签正确渲染）
::v-deep .activity-intro {
  /* 处理段落样式 */
  p {
    margin: 0 0 10px 0;
    line-height: 1.6;
  }

  /* 处理加粗样式 */
  strong, b {
    font-weight: bold;
    color: #333;
  }

  /* 处理颜色样式 */
  span {
    color: inherit; // 继承富文本中的颜色设置
  }

  /* 处理其他可能的标签 */
  em, i {
    font-style: italic;
  }

  /* 确保内容不溢出 */
  max-height: 80px; // 限制高度，避免内容过长
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; // 最多显示3行
  -webkit-box-orient: vertical;
}

.activity-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .header-section {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(to right, #f8f9fa, #e9ecef);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

    .title-container {
      .page-title {
        font-size: 28px;
        color: #2c3e50;
        margin-bottom: 8px;
      }

      .page-subtitle {
        font-size: 16px;
        color: #7f8c8d;
        margin: 0;
      }
    }

    .search-section {
      display: flex;
      width: 100%;
      max-width: 500px;
      margin-top: 15px;

      .search-input {
        flex: 1;
        margin-right: 10px;
      }
    }
  }

  .filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding: 15px 0;
    border-bottom: 1px solid #eee;

    .filter-tags {
      .el-tag {
        margin-right: 10px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  .activity-list {
    .activity-cards {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 25px;

      .activity-card {
        transition: all 0.3s ease;
        border-radius: 12px;
        overflow: hidden;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .card-content {
          display: flex;
          flex-direction: column;
          height: 100%;

          .activity-image {
            height: 200px;
            overflow: hidden;
            position: relative;
          }

          .activity-info {
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;

            .activity-name {
              margin: 0 0 10px;
              font-size: 18px;
              color: #2c3e50;
            }

            .activity-time {
              display: flex;
              align-items: center;
              margin-bottom: 12px;
              color: #7f8c8d;
              font-size: 14px;

              i {
                margin-right: 5px;
              }
            }

            .activity-intro {
              flex: 1;
              color: #555;
              font-size: 14px;
              margin-bottom: 15px;
            }

            .activity-actions {
              display: flex;
              justify-content: space-between;
            }
          }
        }
      }
    }
  }

  .pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 40px;
    padding: 20px 0;
  }
}

@media (max-width: 768px) {
  .activity-page {
    padding: 15px;

    .header-section {
      flex-direction: column;
      align-items: flex-start;

      .search-section {
        width: 100%;
        max-width: none;
        margin-top: 20px;
      }
    }

    .filter-section {
      flex-direction: column;
      align-items: flex-start;

      .view-toggle {
        margin-top: 15px;
        width: 100%;

        .el-radio-group {
          width: 100%;

          .el-radio-button {
            flex: 1;
          }
        }
      }
    }

    .activity-list .activity-cards {
      grid-template-columns: 1fr;
    }
  }
}
</style>
